<?php
/**
 * 海南宝球供应商订单SDK
 * @author hujian
 */

namespace App\Service\VendorClient\ShophnbaoqiuApi;

use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

class ShophnbaoqiuApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shophnbaoqiu';

    private $config = [];

    public function __construct($apiBody=[]) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder($param = [])
    {
        $orderInfo   = $param['supplierOrder'];
        $goodsList   = $param['orderGoods'];
        $order       = $param['order'];
        $binfo       = $param['binfo'];
        $companyInfo = $param['companyInfo'];
        $order_sn    = $orderInfo['supplier_dsn'];
        if (count($goodsList) > 1) {
            return Normal::returnCode(Normal::FAIL, "当前订单不支持多商品下单");
        }
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费
        $deliver_money = $orderInfo['deliver_money'] ?? 0.00;
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //获取下单商品信息
        $requestParam = [];
        // $goodsTotalMoney = 0;
        // $way_tax_fee     = 0;
        foreach ($goodsList as $key => $item) {
            $tax_rate = bcadd('1', (string)$item['tax_rate'], 4);
            $price    = $item['price'];
            $spec_num = $item['spec_num'];
            $quantity = $item['quantity'];
            //单个商品的含税单价
            $singlePrice = bcdiv((string)$price, (string)$spec_num, 3);
            //单个商品的不含税单价
            $goodsPrice      = bcdiv((string)$price, (string)$tax_rate, 3);
            $goodsPrice      = bcdiv((string)$goodsPrice, (string)$spec_num, 3);
            $goodsPrice      = bcmul((string)$goodsPrice, (string)100, 1);
            $goodsPrice      = bcdiv((string)ceil($goodsPrice), 100, 2);
            $buyNum          = $spec_num * $quantity;
            $goodsTotalPrice = bcmul((string)$goodsPrice, (string)$buyNum, 2);
            //商品关税当前币种最小单位（分）
            $goodsCustomsTax = bcsub((string)$singlePrice, (string)$goodsPrice, 2);
            $taxAll          = bcmul((string)$goodsCustomsTax, (string)$buyNum, 2);
            if (!isset($item['supplier_store_code']) || empty($item['supplier_store_code'])) {
                return Normal::returnCode(Normal::FAIL, "订单商品海关备案号不能为空");
            }
            if (!isset($item['supplier_store_id']) || empty($item['supplier_store_id'])) {
                return Normal::returnCode(Normal::FAIL, "订单商品仓库编码不能为空");
            }
            $requestParam[] = [
                'custInnerOrderId'    => $order_sn,//商户内部订单ID，(子订单编号)
                'storeCode'           => $item['supplier_store_id'],//仓库编码，根据实际发货仓库填写 微服务字段defaultStock字段
                'orderId'             => $order_sn,//订单编号
                'orderStatus'         => 'S',//订单状态 （S-订单新增，C-订单取消）
                'receiveName'         => $orderInfo['receive_name'],//收件人姓名
                'receiveProvince'     => $orderInfo['province'],//收件人省
                'receiveCity'         => $orderInfo['city'],//收件人市
                'receiveAddr'         => $orderInfo['receive_address'],//收件人地址
                'receiveCounty'       => $orderInfo['district'],//收件人区
                'receivePhone'        => $orderInfo['recveive_phone'],//	收件人电话
                'payAccount'          => $orderInfo['buyer_phone'],//	订单人ID
                'payerName'           => $orderInfo['buyer_realname'],//	订单人姓名
                'payerDocumentType'   => '01',//订单人证件类型（01:身份证）
                'payerDocumentNumber' => $orderInfo['buyer_idcard'],//订单人证件号码,
                'goodInfo'            => $item['goods_name'],//商品信息
                'customListNo'        => $item['supplier_store_code'],//商品海关备案号  微服务字段declarePlanCode存海关编码
                'gNo'                 => (string)($key + 1),//商品序号
                'applyNum'            => $buyNum,//申报数量
                'payAmount'           => $orderInfo['real_total_money'],//支付金额,
                'goodPrice'           => $goodsPrice,//商品单价,
                'goodTotal'           => $goodsTotalPrice,//商品总价,
                'freight'             => $deliver_money,//运费,
                'tax'                 => $taxAll,//税款,
                'discount'            => '0.00',//优惠金额,
                'orderDate'           => $order_time,//订单日期（格式”yyyy-MM-dd HH:mm:ss”）
                'payDate'             => $pay_time,//付款时间（格式”yyyy-MM-dd HH:mm:ss”）
                'payTransactionNo'    => $order['paySerial'] ?? $apply_extends['paySerial'],//支付交易号
                'payMethod'           => $order['payCommanyName'] ?? $apply_extends['payCommanyName'],//支付方式
                'payMerchantCode'     => $order['payCommanyCode'] ?? $apply_extends['payCommanyCode'],//支付企业代码
                'payTransactionName'  => $order['payCommanyName'] ?? $apply_extends['payCommanyName'],//支付企业名称
                // 'note' => '-----',//备注
                // 'goodBatchNo' => '-----',//指定批次
            ];
        }
        $data = [
            'method' => 'createOrder',
            'data'   => [
                'eOrders'   => $requestParam,
                'userId'    => $this->config['USER_ID'],
                'timeStamp' => date('YmdHis')
            ]
        ];
        return $this->execute($data);
    }

    /**
     * 查询商品
     * @param array $param
     */
    public function queryGoodsList($param=[])
    {
        $data = [
            'method' => 'queryGoods',
            'data'   => [
                'userId'    => $this->config['userId'],
                'timeStamp' => date('YmdHis')
            ]
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        $stringA = json_encode($data);
        $stringB = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $stringA);
        $stringF = $stringB . $this->config['appSecret'];
        return md5($stringF);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($param = [])
    {
        if (!isset($this->config[$param['method']])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config['baseurl'];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $sign      = $this->sign($param['data']);
        $parameter = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $param['data'],
                'method' => 'post',
                'format' => 'json',
                'header' => [
                    "method: {$this->config[$param['method']]}",
                    "sign: {$sign}",
                ],
            ],
        ];
        if( in_array($param['method'],['queryGoods']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask   = current($resTask);
        $result    = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] == 200) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['resultDesc'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $requestParam = [
            $param['supplier_dsn'],
        ];
        $data = [
            'method' => 'orderExpress',
            'data'   => [
                'orderIds'  => $requestParam,
                'userId'    => $this->config['USER_ID'],
                'timeStamp' => date('YmdHis'),
            ],
        ];
        return $this->execute($data);
    }
}
